'use strict';

const Controller = require('egg').Controller;
const jwt = require("jsonwebtoken")
class HomeController extends Controller {
  async login() {
    const { ctx, service } = this;
    const { username, password } = ctx.request.body;
    if (username && /\w{4,6}/.test(password)) {
      const result = await service.home.login(username, password)
      if (result.length) {
        console.log(result)
        let { role_id, role_name, username, id } = result[0];
        let token = jwt.sign({ uid: id }, "123456", { expiresIn: 60 * 60 })
        ctx.body = {
          code: 1,
          msg: "登录成功",
          token,
          role_id,
          role_name,
          username
        }
      } else {
        ctx.body = {
          code: 1,
          msg: "登录失败"
        }
      }
    } else {
      ctx.body = {
        code: 2,
        msg: "参数有误"
      }
    }
  }
  async menuList() {
    const { ctx, service } = this;
    const { role_id } = ctx.request.query;
    if (role_id) {
      const result = await service.home.menuList(role_id)
      if (result.length) {
        ctx.body = {
          code: 1,
          data: result
        }
      } else {
        ctx.body = {
          code: 0,
          msg: "登录失败"
        }
      }
    } else {
      ctx.body = {
        code: 2,
        msg: "参数有误"
      }
    }
  }
}

module.exports = HomeController;
